(function(D){
	D.initCollections = function(){
		var collections = {},
		    labels = [];

		D.request("listCollections.txt", {}, function(results){
				var label;
				for(var i=0; i<results.length; i+=1){
					label = decodeURIComponent(results[i].collectionLabel.value);
					collections[label] = results[i].collectionId.value;
					labels[i] = label;
				}
			}
		);
		D.autocomplete(labels, document.getElementById("openCollection"), function(item){
			var timestamp = new Date( ).getTime( ),
			    collectionId = "http://desanti.org/collections/"+timestamp;

			if(collections[item]){
				D.newLine(collections[item]);
			} else {
				D.request("newCollection.txt", 
					{
						"collectionLabel": encodeURIComponent(item),
						"collectionId": collectionId,
						"timestamp": timestamp,
						"user": D.userName()
					}, function(){
						D.newLine(collectionId);
						D.initCollections();
					},
					true, true
				);
			}
		});
	}
})(DESANTI);
